/*
 * @Author: jingfuu@163.com
 * @Date: 2024-09-14 17:02:45
 * @LastEditTime: 2024-11-21 16:56:53
 * @Description: 自定义的异常过滤器，拦截异常，返回统一的对象
 */
import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  BadRequestException,
  Logger,
} from '@nestjs/common';
import { Response } from 'express';
import { R } from '../R';

@Catch(BadRequestException)
export class BadRequestExceptionFilter implements ExceptionFilter {
  private readonly logger = new Logger(BadRequestExceptionFilter.name);

  catch(exception: BadRequestException, host: ArgumentsHost) {
    if (exception.name == 'BadRequestException')
      this.logger.error(exception.stack);
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status = exception.getStatus();
    response
      .status(200)
      .json(R.fail((exception.getResponse() as any).message, status));
  }
}
